//
//  USPSTrackInfo.m
//  PostalTracker
//
//  Created by Aleksandr Batsuev on 1/30/11.
//  Copyright 2011 batsuev.com. All rights reserved.
//

#import "USPSTrackInfo.h"

#define NO_DATA @"No information found";

@implementation USPSTrackInfo

NSURLConnection *connection;

-(id)init
{
	if (![super init]) return nil;
	
	requestURL = @"http://trkcnfrm1.smi.usps.com/PTSInternetWeb/InterLabelInquiry.do";
	trackingParamName = @"origTrackNum";
	
	return self;
}

-(NSData*)createRequestData:(NSString*)trackingNumber
{
	NSString *encodedParameters = [[NSString alloc] initWithFormat:@"%@=%@",trackingParamName,trackingNumber];
	NSData *postData = [encodedParameters dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
	return postData;
}

-(NSString*)parseResult:(NSData*) data
{
	if (data == nil) return NO_DATA;
	
	NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
	
	NSXMLDocument *tableXML = [[NSXMLDocument alloc] initWithXMLString:result options:NSXMLDocumentTidyHTML error:nil];
	NSArray *lastEntry = [tableXML nodesForXPath:@"//table[@summary='This table formats the detailed results.']/tr[2]/td[2]" error:nil];
	
	if ([lastEntry count] != 1) return NO_DATA;
	
	NSXMLNode *lastEntryNode = [lastEntry objectAtIndex:0];
	
	return [lastEntryNode stringValue];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	[self setStringResult:[self parseResult:data]];
	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"trackingInfoLoaded" object:(id)self];
}

-(void)getInfo:(NSString*)trackingNumber 
{
	if (connection != nil)
		[connection cancel];
	
	NSData *postData = [self createRequestData:trackingNumber];
	
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:requestURL]];
	[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
	[request setHTTPMethod:@"POST"];
	[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:postData];
	[request setValue:[NSString stringWithFormat:@"%d", [postData length]] forHTTPHeaderField:@"Content-Length"];
	
	connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
}

-(void)showDetailedInfo:(NSString*)trackingNumber
{
	NSURL *url = [ [ NSURL alloc ] initWithString: @"http://www.cnn.com" ];
	NSWorkspace * ws = [NSWorkspace sharedWorkspace];
	[ws openURL:url];
}

-(NSString*)stringResult { return stringResult; }
-(void)setStringResult:(NSString *)value {
	stringResult = [NSString stringWithString:value];
}

@end
